#include "regx51.h"
#include "math.h"

//拓展：
//基础部分是利用定时器的中断实现每一秒钟的计数，并显示时间的程序。
//除此之外还可以利用轮询的功能实时查看定时器是否溢出，以及实现秒表功能。

//#define Work1
#define Work2


unsigned char code LED_Table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f
                                //0  1  2  3  4  5  6  7  8  9
                                ,0x77,0x7c,0x39,0x5e,0x79,0x71,0x40,0x00};
                                //A  B  C  D  E  F  -  Down


                                
void Delay_ms(unsigned int t)
{
    unsigned int i,j;
    for(i=0;i<t;i++)
    {
        for(j=0;j<100;j++)
        {
            ;0
        }
    }
}

void Show_Seg8_ShowTime(unsigned char* Time_Arr)
{
    unsigned char i=0;
    unsigned char scan=0xfe;

    for(i=0;i<8;i++)
    {
        P2=0xff;
        P0=LED_Table[Time_Arr[i]];
        P2=scan;
        scan=(scan<<1)+1;
        Delay_ms(5);
    }
}

void Switch_TimeNum(unsigned long int Time_Num,unsigned char* Time_Arr)
{
    unsigned char Hour=0,Minute=0,Second=0;
    Hour=Time_Num/3600%24;
    Minute=(Time_Num%3600)/60;
    Second=Time_Num%60;
    Time_Arr[0]=Hour/10;
    Time_Arr[1]=Hour%10;
    Time_Arr[3]=Minute/10;
    Time_Arr[4]=Minute%10;
    Time_Arr[6]=Second/10;
    Time_Arr[7]=Second%10;
}

void Timer_Init(void)
{
	TMOD=0x02;
    TL0=0x9c;
    TH0=0x9c;
    ET0=1;
    EA=1;
    TR0=1;
}



unsigned long int Time_Num=86390;    //一天86400秒


void main()
{
    unsigned char Time_Arr[8]={0,0,16,0,0,16,0,0};
    
    #ifdef Work2
    unsigned int Count=0;
    #endif

    Timer_Init();
    while(1)
    {
        #ifdef Work2
        if(TF0==1)
        {
            TF0=0;
            Count++;
            if(Count==23)//本应该是10000，但由于循环和数码管显示的关系，导致每秒钟的计数次数远小于10000
            {
                Count=0;
                Time_Num++;
            }

        }

        #endif
        Switch_TimeNum(Time_Num,Time_Arr);
        Show_Seg8_ShowTime(Time_Arr);
    }
}

#ifdef Work1
void Timer0_ISR(void) interrupt 1
{
    static unsigned int Count=0;
    Count++;
    if(Count==10000)
    {
        Count=0;
        Time_Num++;
    }
}
#endif
